/*
 * @lc app=leetcode.cn id=863 lang=typescript
 *
 * [863] 二叉树中所有距离为 K 的结点
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

function distanceK(root: TreeNode | null, target: TreeNode | null, k: number): number[] {
  const parents: Map<number, TreeNode> = new Map();
  const findParent = (node: TreeNode) => {
    if (node === null) return;
    if (node.left !== null) {
      parents.set(node.left.val, node);
      findParent(node.left);
    }
    if (node.right !== null) {
      parents.set(node.right.val, node);
      findParent(node.right);
    }
  };
  findParent(root);

  const ans: number[] = [];
  const findAns = (node: TreeNode | null, from: TreeNode | null, depth: number) => {
    // 哈希中没有找到结果返回的是undefined，这里需要特判一下
    if (node === null || node === undefined) return;
    if (depth === k) {
      ans.push(node.val);
      return;
    }
    if (node.left !== from) {
      findAns(node.left, node, depth + 1);
    }
    if (node.right !== from) {
      findAns(node.right, node, depth + 1);
    }
    if (parents.get(node.val) !== from) {
      findAns(parents.get(node.val), node, depth + 1);
    }
  };
  findAns(target, null, 0);

  return ans;
}
// @lc code=end
